package server;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Hashtable;

import entry.Entry;
import event.Event;
import event.EventHandler;

public class DirectoryEventHandler implements EventHandler {

	@Override
	public void handle(Event e) {
		if (e.type == Event.DIR_TYPE) {
			byte[] message = e.message;

			ArrayList<Entry> results = null;
			try {
				ObjectInputStream is = new ObjectInputStream(
						new ByteArrayInputStream(message));

				results = (ArrayList<Entry>) is.readObject();
			} catch (IOException ex) {
				// TODO Auto-generated catch block
				ex.printStackTrace();
			} catch (ClassNotFoundException ex) {
				// TODO Auto-generated catch block
				ex.printStackTrace();
			} finally {
				if (results != null) {
					System.out.println("> Start receive peer file listing");

					Model model = Model.getInstance();
					Hashtable<String, Entry> items = model.items;

					for (Entry b : results) {
						items.put(b.key, new Entry(e.parameters, b.value));
						System.out.println("\t> " + e.parameters + " - "
								+ b.key);
					}

					System.out.println("> End receive peer file listing: "
							+ e.parameters);
				}
			}
		}
	}
}
